package com.example.rabbitmq.demo3_pub_and_returned_confirm;

import com.example.rabbitmq.enums.ExchangeEnum;
import com.example.rabbitmq.enums.RabbitmqQueueNamesEnum;
import com.example.rabbitmq.enums.RoutingKeyEnum;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;

/**
 * @Author songyahui
 * @Date 2023/7/14 9:05
 * @Description
 */
public class Consumer {

    public static void consumeMessage(Channel channel) throws IOException {
        //声明死信和普通交换机 类型未direct
        channel.exchangeDeclare(ExchangeEnum.NORMAL_EXCHANGE.name, BuiltinExchangeType.DIRECT);

        channel.queueDeclare(RabbitmqQueueNamesEnum.QUEUE_NORMAL.queueName, false, false, false, null);
        //绑定普通交换机和队列
        channel.queueBind(RabbitmqQueueNamesEnum.QUEUE_NORMAL.queueName, ExchangeEnum.NORMAL_EXCHANGE.name, RoutingKeyEnum.NORMAL.name());
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), "UTF-8");
            System.out.println("普通消费："+msg);
            channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
        };
        /**
         * 最后一个回调实例是消费端取消消费时调用，取消消费一般是消费端维护、宕机或异常等断掉连接的情况
         */
        channel.basicConsume(RabbitmqQueueNamesEnum.QUEUE_NORMAL.queueName, false, deliverCallback, System.out::println);
    }
}
